from django.contrib.auth import login
from rest_framework.authentication import SessionAuthentication, TokenAuthentication
from functools import wraps
from rest_framework.exceptions import AuthenticationFailed


class CsrfExemptSessionAuthentication(SessionAuthentication):
    def enforce_csrf(self, request):
        return


def token_login_required(view_func):

    @wraps(view_func)
    def _wrapped_view(request, *args, **kwargs):

        if hasattr(request, 'user') and request.user.is_authenticated:
            return view_func(request, *args, **kwargs)

        token = request.GET.get('token')  # 从 GET 参数中获取 Token

        if not token:
            return view_func(request, *args, **kwargs)

        try:
            # 验证 Token 并获取用户
            auth = TokenAuthentication()
            user, _ = auth.authenticate_credentials(token)
            login(request, user)
            return view_func(request, *args, **kwargs)
        except AuthenticationFailed:
            return view_func(request, *args, **kwargs)

    return _wrapped_view
